package com.bigben.controller;

import com.bigben.Exception.DictNotFountException;
import com.bigben.mapper.CommDictionaryMapper;
import com.bigben.service.DictionaryService;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.bigben.entites.CommDictionary;
import org.springframework.web.servlet.tags.form.ErrorsTag;
import com.bigben.dto.Error;

import java.util.List;


/**
* @Author: zhaoben
* @Date: 2016/12/18 16:27
* @Desc: CommDictionary相关操作
*/
@RestController
@RequestMapping("/dict")
public class DictionaryController {

    @Autowired
    private DictionaryService dictionaryService;

    /**
     * @Desc: 根据父ID获取对应子节点的字典值
     * @Author: zhaoben
     * @Date: 2016/12/18 16:10
     * @Param: String 类型 prentId
     * @Result: CommDictionary 列表
     */
    @RequestMapping(value = "/parent/{parentId}", method = RequestMethod.GET, produces = "application/json")
    public List<CommDictionary> getDictByParentId(@PathVariable("parentId") String parentId) {
        List<CommDictionary> result = dictionaryService.getDictByParentId(parentId);
        if (result.size() == 0) {
            throw new DictNotFountException(parentId);
        }
        return result;
    }

    /**
     * @Desc: 获取所有数据字典值
     * @Author: zhaoben
     * @Date: 2016/12/18 16:10
     * @Param: null
     * @Result: CommDictionary 列表
     */
    @RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json")
    public List<CommDictionary> getAll() {
        return dictionaryService.getAll();
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST, consumes = "application/json")
    public void update(@RequestBody List<CommDictionary> dicts) {
        dictionaryService.update(dicts);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST, consumes = "application/json")
    public CommDictionary saveDictionary(@RequestBody CommDictionary dictionary) {
        System.out.println(dictionary.getDictCode());
        return dictionary;
    }

    /**
     * DictNotFount异常处理
     *
     * @Author: zhaoben
     * @Date: 2016/12/18 15:36
     */
    @ExceptionHandler(DictNotFountException.class)
    public Error DictNotFound(DictNotFountException e) {
        String userId = e.getDictId();
        Error error = new Error(HttpStatus.NOT_EXTENDED.value(), "ID（" + userId + ") not found");
        return error;
    }

}
